在多文字檔中搜尋關鍵字
- 第一層for迴圈使用了os.walk()遞迴取得路徑下的所有檔案
- 第二層for迴圈依序處理.txt、.py、.c三中副檔名的檔案
- fnmatch.filter()過濾符合副檔名的檔案
import os, fnmatch
path = "./text"
keyword = "for"
for root, dirs, files in os.walk(path):
for ext in ['txt', 'py', 'c']:
for fname in fnmatch.filter(files, '*.' + ext):
file = os.path.join(path, fname)
with open(file, "r") as fp:
num = 1
for line in fp.readlines():
if keyword in line:
print("檔案: ", fname)
print(num, ":", str(line))
num = num + 1
改用正規表達是搜尋關鍵字if和for
import os, fnmatch
path = "./text"
pattern = re.compile(‘for’ |’if’)
for root, dirs, files in os.walk(path):
for ext in ['txt', 'py', 'c']:
for fname in fnmatch.filter(files, '*.' + ext):
file = os.path.join(path, fname)
with open(file, "r") as fp:
num = 1
for line in fp.readlines():
if re.search(pattern, line):
print("檔案: ", fname)
print(num, ":", str(line))
num = num + 1